/**
 * 歌词无法精确到毫秒  !!!!!  
 */
import React, { useState, useEffect, useRef, useCallback } from 'react'

import { changePlayingMusicAfter, changePlayingMusicLater } from '@/store/actions/common'
import { connect } from 'react-redux'
import { Slider } from 'antd-mobile'
import { setBackLogTime } from '@/utils/method'
import PLayingList from './playing-list/playing-list'
import Layer from '../layer/index' 

import './player.scss'

let timer = null

const Player = (props) => {
  const { name, img, mp3Url, duration, lyric, id } = props
  const musicDom = useRef()
  const [stop, setStop] = useState(true) // 暂停与否
  const [isDetail, setIsDetail] = useState(false) // 是否是大详情
  const [showText, setShowText] = useState(false) // 是否显示歌词
  const [durationTime, setDurationTime] = useState(0) // 播放器得秒数
  const [doneWidth, setDoneWidth] = useState(0) // 小播放器得进度条width
  const [lrcArray, setLrcArray] = useState([]) // 歌词
  const [showPlayingList, setShowPlayingList] = useState(false) // 是否显示正在播放的list
  
  useEffect(() => {
    // 监听 img 当前歌曲的图片,因是模拟接口,所以 mp3Url 是假的
    // 唯一可监听的是 name, img,二选一
    const audio = musicDom.current
    audio.currentTime = 0
    time(audio)
    // 判断此时的播放状态
    if (!stop) {
      audio.play()
      setStop(false)
    }
    // 解析歌词
    let allLrc = [] // 解析第一步,放的是所有的歌词,带有时间
    let lrcArrayVar = [] // 成品
    if (lyric) {
      allLrc = lyric.split('\n')
      for (let index = 0; index < allLrc.length; index++) {
        const element = allLrc[index].split("]");
        if (element.length > 1) {
          let offset = element[0].substring(1, element[0].length-1);
					let text = element[1];
          if (text !== '') {
            lrcArrayVar.push({ time: getlrcTime(offset), text })
          }
        }
      }
    }
    setLrcArray(lrcArrayVar)
  }, [props])


  useEffect(() => {
  }, [])


  // 处理接口返回的时间格式,因暂时无法精准匹配,因此只选择了匹配到秒,后续在想办法
  const getlrcTime = (time) => {
    let tl = time.split(":")
    const sec = parseFloat(tl[0]) * 60 + parseFloat(tl[1])
    if ((sec + '').indexOf('.') === -1) {
      return parseFloat(tl[0]) * 60 + parseFloat(tl[1])
    }
    return sec.toFixed(0);
    // switch(tl.length){
    //   case 1 :
    //     return parseFloat(tl[0]);
    //   case 2:
    //     return parseFloat(tl[0]) * 60 + parseFloat(tl[1]);
    //   case 3:
    //     return parseFloat(tl[0]) * 3600 + parseFloat(tl[1]) * 60 + parseFloat(tl[2]);
    // }
  }

  // didmount
  useEffect(() => {
    const audio = musicDom.current
    audio.addEventListener('timeupdate', function(){
      if (!isNaN(audio.currentTime)) {
        if(doneWidth >= 100){
          setDoneWidth(0); // 当播放完成，进度条跳到开始
          setDurationTime(0) // 当前秒数归零
        }
        const sec = audio.currentTime.toFixed(0) + ''
        lrcBoxroll(sec)
      };
    }, false)
  })

  // 歌词滚动, 动态设置歌词盒子的 marginTop, 时间相同的话, 给当前歌词高亮的同时赋予其他歌词黑色
  const lrcBoxroll = (sec) => {
    const lrcBox = document.getElementById('lrc-box')
    const lrcItems = document.querySelectorAll('.lrc-item')

    lrcArray && Array.isArray(lrcArray) && lrcArray.map((item, index) => {
      if (item.time == sec) {
        for (let i = 0; i < lrcItems.length; i++) {
          lrcItems[i].style.color = 'black'
        }
        lrcBox.style.marginTop = (-0.92 * (index + 1)) + 'rem'
        lrcItems[index].style.color = 'red'
      }
    })
  }

  // 每一秒钟执行获取一次 audio 得播放时间
  const time = () => {
    timer = setInterval(() => {
    const audio = musicDom.current
      if (audio && audio.currentTime) {
        const currentTime = Math.floor(audio.currentTime)
        if (doneWidth < 100) {
          setDoneWidth((currentTime / Math.floor(duration / 1000) * 100).toFixed(2))
          setDurationTime(currentTime)
        } else {
          clearInterval(timer)
        }
      }
    }, 1000)
  }

  // 暂停 和 播放事件
  const stopMusic = () => {
    const audio = musicDom.current
    if (stop) {
      audio.play()
      time()
    } else {
      audio.pause();
      clearInterval(timer)
    }
    setStop(!stop)
  }

  // 打开详情播放得弹窗
  const jumpDetail = () => {
    setIsDetail(true)
  }

  // 拖动进度条
  const changeMusicTime = (value) => {
    const audio = musicDom.current
    if (timer) {
      clearInterval(timer)
      audio.pause();
    }
    const changeTime = value / 100000 * duration
    audio.currentTime = changeTime

    setDurationTime(changeTime)
    setDoneWidth(value)
    time()
    if (!stop) {
      audio.play();
    }
  }

  // 弹窗部分 详情
  const renderDetail = () => {
    return (
      <div className='detail' style={{ display: `${ isDetail ? 'block' : 'none' }` }}>
        <div className='title-btn'>
          <i className='iconfont icon-zhankai1' onClick={ () => {
            setIsDetail(false)
            setShowText(false)
            } }></i>
          <div className='title-name' onClick={ () => setShowText(false) }>
            <p className='ani' id='top-name'>{ name }</p>
          </div>
          <p className='title-name worp' onClick={ () => setShowText(true) }>歌词</p>
          <i className='iconfont icon-zhankai1'></i>
        </div>
        <div className='mussic-middle'>
          <div className={ `${ showText ? 'music-img-box to-left' : 'music-img-box to-middle' }` }>
            <div>
              <img src={ img } alt='歌曲图片' className='music-img' />
            </div>
            <div className='music-msg'>
              <div className='msg'>
                <p className='music-name worp'>{ name }</p>
                <p className='music-author worp'>{ name }</p>
              </div>
              <div className='love-music'>
                <i className={ `icon-yun iconfont join-my-love` } />
                <i className={ `icon-icon_huabanfuben iconfont join-my-love` } />
              </div>
            </div>
          </div>
          <div className={`${ showText ? 'music-text-box worp to-left' : 'music-text-box worp to-right' }`}>
            <div className='lrc'>
              <div className='lrc-box' id='lrc-box'>
                {
                  lrcArray && Array.isArray(lrcArray) && lrcArray.map(item => {
                    return <p className='lrc-item' key={ item.time + item.text }>
                      {
                        item.text
                      }
                    </p>
                  })
                }
              </div>
            </div>
          </div>
        </div>
        <div className='music-optios'>
          <i className={ `icon-huatong iconfont music-options-icon` } />
          <i className={ `icon-offer iconfont music-options-icon` } />
          <i className={ `icon-xiazai iconfont music-options-icon` } />
          <i className={ `icon-xinxi iconfont music-options-icon` } />
          <i className={ `icon-dian iconfont music-options-icon` } />
        </div>
        <div className='change-music'>
          <div className='sliber'>
            <Slider
              defaultValue={0}
              value={ doneWidth }
              min={0}
              max={100}
              onChange={changeMusicTime}
              onAfterChange={changeMusicTime}
            />
            <p className='sliber-time'>
              <span>{ setBackLogTime(durationTime * 1000) }</span>
              <span>{ setBackLogTime(duration) }</span>
            </p>
          </div>
          <div className='change-music-btn'>
            <i className={ `icon-ziyuan iconfont music-change` } onClick={ () => changePlayingMusicAfter(id) } />
            <i className={ `icon-shangyishou iconfont music-change-next` } onClick={ () => changePlayingMusicLater(id) } />
            <i
              className={
                `${ stop ? 'icon-zanting' : 'icon-zanting1' }
                iconfont music-change-suspend`
              }
              onClick={ () => stopMusic()
              }
            />
            <i className={ `icon-xiayishou iconfont music-change-next` } />
            <i className={ `icon-gengduo iconfont music-change` } onClick={ () => setShowPlayingList(true)} />
          </div>
        </div>
      </div>
    )
  }

  const renderBottomPlay = () => {
    return <div className='player-box' style={{ display: `${ !isDetail ? 'block' : 'none' }` }}>
      <div className='player-box-top'>
        <img
          src={ img }
          alt='歌曲图片'
          className='player-box-top-img'
        />
      </div>
      <div className='player-box-bottom'>
        <div className='player-box-bottom-circle'>
        </div>
        <div className='player-box-bottom-name' onClick={jumpDetail}>
          <p className='worp'>{ name }</p>
          <div className='plan-audio' id='plan-box'>
            <div
              className='plan-audio-done'
              id='done-plan'
              style={{ width: doneWidth + '%' }}></div>
          </div>
        </div>
        <div className='player-box-bottom-option' onClick={ stopMusic }>
          {
            stop
              ? <i className='iconfont icon-zanting'></i>
              : <i className='iconfont icon-zanting1'></i>
          }
        </div>
        <i className='iconfont icon-gengduo' onClick={ () => setShowPlayingList(true)}></i>
      </div>
    </div>
  }

  return (
    <div className='player'>
      <audio
        src={mp3Url}
        preload={true}
        ref={ musicDom }
        id="music"
      ></audio>
      {
        renderDetail()
      }
      {
        renderBottomPlay()
      }
      <Layer show={showPlayingList} close={ () =>setShowPlayingList(false)} />
      <PLayingList detail={ isDetail } show={showPlayingList}  close={ () => setShowPlayingList(false) } />
    </div>
  )
}

const mapStateToProps = (store) => {
 return store.common
}

const mapDispatchToProps = (dispatch) => {
  return {
    changePlayingMusicAfter(data) {
      dispatch(changePlayingMusicAfter(data))
    },
    changePlayingMusicLater(data) {
      dispatch(changePlayingMusicLater(data))
    }
  }
 }

export default connect(mapStateToProps, mapDispatchToProps)(Player)